﻿using System.Collections.Generic;
using System.Data.SQLite;
using StudentManagementSystem.Models;

namespace StudentManagementSystem.Data
{
    public class LogRepository
    {
        private readonly string _connectionString;


        public LogRepository(string connectionString)
        {
            _connectionString = connectionString;
        }

        public void Add(LogEntry log)
        {
            using var connection = new SQLiteConnection(_connectionString);
            connection.Open();

            using var command = new SQLiteCommand(
                "INSERT INTO Logs (Timestamp, Action, Details) VALUES (@Timestamp, @Action, @Details)",
                connection);

            command.Parameters.AddWithValue("@Timestamp", log.Timestamp);
            command.Parameters.AddWithValue("@Action", log.Action);
            command.Parameters.AddWithValue("@Details", log.Details);

            command.ExecuteNonQuery();
        }

        public IEnumerable<LogEntry> GetAll()
        {
            var logs = new List<LogEntry>();

            using var connection = new SQLiteConnection(_connectionString);
            connection.Open();

            using var command = new SQLiteCommand("SELECT * FROM Logs ORDER BY Timestamp DESC", connection);
            using var reader = command.ExecuteReader();

            while (reader.Read())
            {
                logs.Add(new LogEntry
                {
                    Id = reader.GetInt32(0),
                    Timestamp = reader.GetDateTime(1),
                    Action = reader.GetString(2),
                    Details = reader.IsDBNull(3) ? null : reader.GetString(3)
                });
            }

            return logs;
        }
    }
}